package com.acme.bankapp.apps;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientApplication {

	private final int port;
	private final String serverIp;

	public ClientApplication(String serverIp, int port) {
		this.serverIp = serverIp;
		this.port = port;
	}

	public void start() {

		System.out.println("Client started");

		try (Socket kkSocket = new Socket(serverIp, port);
				PrintWriter out = new PrintWriter(kkSocket.getOutputStream(),
						true);
				BufferedReader in = new BufferedReader(new InputStreamReader(
						kkSocket.getInputStream()));) {

			BufferedReader stdIn = new BufferedReader(new InputStreamReader(
					System.in));

			String fromServer;
			String fromUser;

			while ((fromServer = in.readLine()) != null) {
				fromServer = fromServer.replace("\\n", "\n");
				System.out.println("Server: " + fromServer);

				fromUser = stdIn.readLine();
				if (fromUser != null) {
					System.out.println("Client: " + fromUser);
					out.println(fromUser);
				}
			}
		} catch (UnknownHostException e) {
			System.err.println("Don't know about host " + serverIp);
		} catch (IOException e) {
			System.err.println("Couldn't get I/O for the connection to "
					+ serverIp);
		}

	}

}
